#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "maxSubArray.h"

using namespace std;

int main(int argc, char **argv) {
    if (argc != 2) {
        cout << "Usage: " << argv[0] << " file_name" << endl;
        return 0;
    }

    string file_name(argv[1]);
    fstream fs;
    fs.open(file_name.c_str(), fstream::in);
    if (!fs.is_open()) {
        cout << "File " << file_name << " open error!" << endl;
        return 1;
    }

    int elem_num;
    string str;
    fs >> str;
    elem_num = atoi(str.c_str());
    if (elem_num <= 0) {
        cout << "Invalid element num " << elem_num << "!" << endl;
        return 1;
    }

    int *array = new int[elem_num];
    if (array == NULL) {
        cout << "Allocate array buffer error!" << endl;
        return 1;
    }

    int loc = 0;
    while (fs >> str) {
        if (str.empty()) {
            break;
        }
        array[loc++] = atoi(str.c_str());
    }

    if (loc != elem_num) {
        cout << "Incorrect number of elements." << endl;
        return 1;
    }

    int start, end;
    int max_sum;
    bool ret_code;
    ret_code = maxSubArray(array, elem_num, max_sum, start, end);
    if (ret_code == false) {
        cout << "Find max sub array error!" << endl;
    }
    else {
        cout << "Max sub of subarray is:" << max_sum << "." << endl;
        cout << "Start from elem " << start << " to elem " << end << "." << endl;
    }

    return 0;
}

